package com.tianji.jersey.resource.client;

import java.io.StringReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class XmlUnmarshaller<T> {
	private Log log = LogFactory.getLog(XmlUnmarshaller.class);
	private String contextPath;
	private String xmlStr;

	public XmlUnmarshaller(String contextPath, String xmlStr) {
		this.contextPath = contextPath;
		this.xmlStr = xmlStr;
	}

	public XmlUnmarshaller(Class clazz, String xmlStr) {
		this.contextPath = clazz.getPackage().getName();
		this.xmlStr = xmlStr;
	}

	public T unmarshal() {
		if (xmlStr == null) {
			return null;
		}

		try {
			JAXBContext context = JAXBContext.newInstance(contextPath);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			StringReader reader = new StringReader(xmlStr);
			T object = (T)unmarshaller.unmarshal(reader);
			reader.close();
			return object;
		} catch (JAXBException e) {
			if (log.isErrorEnabled()) {
				log.error("JAXBException, " + e);
			}
		}

		return null;
	}
}
